<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .list{
      width: 200px;
      height: 150px;
      background-color: skyblue;
      overflow:auto;
    }
    .news{
      height: 30px;
    }
  </style>
</head>
<body>
  <div id="test"></div>
  
  <!-- 引入react核心库 -->
  <script src="../lib/17.0.1/react.development.js"></script>
  <!-- 用于支持react操作DOM -->
  <script src="../lib/17.0.1/react-dom.development.js"></script>
  <!-- 用于将jsx转为js -->
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  
  <script type="text/babel">
    // 创建组件
    class NewsList extends React.Component{
      state={newsArr:[]}

      componentDidMount(){
        setInterval(() => {
          //获取原状态
          const {newsArr}=this.state;
          //模拟一条新闻
          let news='新闻'+(newsArr.length+1);
          //更新状态
          this.setState({newsArr:[news,...newsArr]});
        }, 1000);
      }
      getSnapshotBeforeUpdate(){
        let height=this.refs.list.scrollHeight;
        return height;
      }

      componentDidUpdate(preProps,preState,height){
        this.refs.list.scrollTop+=this.refs.list.scrollHeight-height;
      }
      render(){
        const {newsArr}=this.state;
        return(
          <div className='list' ref='list'>
            {
              newsArr.map((item,index)=>{
                return <div key={index} className='news'>{item}</div>
              })
            }
          </div>
        )
      }
    }
    //渲染组件
    ReactDOM.render(<NewsList/>,document.getElementById('test'))
  </script>
</body>
</html>